// pages/thief/game/index.js
Page({
  data: {
    // 游戏状态
    gameState: {
      isPlaying: false,
      isPaused: false,
      level: 1,
      score: 0,
      lives: 3,
      timeRemaining: 60,
      combo: 0,
      maxCombo: 0
    },
    
    // 游戏配置
    gameConfig: {
      canvasWidth: 750,
      canvasHeight: 1000,
      playerSpeed: 5,
      emotionSpeed: 3,
      spawnRate: 0.02,
      powerUpRate: 0.005
    },
    
    // 玩家角色
    player: {
      x: 375,
      y: 800,
      width: 60,
      height: 60,
      emoji: '🥷',
      speed: 5,
      invulnerable: false,
      powerUp: null,
      powerUpTime: 0
    },
    
    // 情感物品
    emotions: [],
    
    // 道具
    powerUps: [],
    
    // 粒子效果
    particles: [],
    
    // 游戏统计
    gameStats: {
      totalGames: 0,
      bestScore: 0,
      totalEmotionsCaught: 0,
      totalTimePlayed: 0,
      averageCombo: 0
    },
    
    // UI状态
    showGameOver: false,
    showPause: false,
    showInstructions: false,
    showLeaderboard: false,
    
    // 排行榜
    leaderboard: [
      { rank: 1, name: '心情大师', score: 15680, level: 12 },
      { rank: 2, name: '情感猎手', score: 12450, level: 10 },
      { rank: 3, name: '偷心高手', score: 9870, level: 8 },
      { rank: 4, name: '你', score: 0, level: 1 }
    ],
    
    // 动画状态
    animations: {},
    
    // 音效状态
    soundEnabled: true,
    
    // 触摸控制
    touchStartX: 0,
    touchStartY: 0,
    
    // 情感类型配置
    emotionTypes: [
      { type: 'happy', emoji: '😊', color: '#FFD700', points: 10, speed: 1 },
      { type: 'love', emoji: '💕', color: '#FF69B4', points: 20, speed: 1.2 },
      { type: 'excited', emoji: '🤩', color: '#FF6347', points: 15, speed: 1.5 },
      { type: 'calm', emoji: '😌', color: '#87CEEB', points: 25, speed: 0.8 },
      { type: 'angry', emoji: '😠', color: '#FF4500', points: -10, speed: 2 },
      { type: 'sad', emoji: '😢', color: '#4169E1', points: -5, speed: 1.3 }
    ],
    
    // 道具类型配置
    powerUpTypes: [
      { type: 'shield', emoji: '🛡️', duration: 5000, effect: 'invulnerable' },
      { type: 'magnet', emoji: '🧲', duration: 8000, effect: 'attract' },
      { type: 'slow', emoji: '⏰', duration: 6000, effect: 'slowMotion' },
      { type: 'double', emoji: '✨', duration: 10000, effect: 'doublePoints' }
    ]
  },

  onLoad(options) {
    this.initGame();
    this.loadGameStats();
  },

  onShow() {
    // 恢复游戏音乐
    if (this.data.gameState.isPlaying && !this.data.gameState.isPaused) {
      this.resumeBackgroundMusic();
    }
  },

  onHide() {
    // 暂停游戏
    if (this.data.gameState.isPlaying) {
      this.pauseGame();
    }
  },

  // 初始化游戏
  initGame() {
    const ctx = wx.createCanvasContext('gameCanvas', this);
    this.ctx = ctx;
    
    // 初始化动画
    this.initAnimations();
    
    // 设置画布尺寸
    // 使用新API替代wx.getSystemInfoSync
    const windowInfo = wx.getWindowInfo();
    const canvasWidth = windowInfo.windowWidth;
    const canvasHeight = windowInfo.windowHeight * 0.7;
    
    this.setData({
      'gameConfig.canvasWidth': canvasWidth,
      'gameConfig.canvasHeight': canvasHeight,
      'player.x': canvasWidth / 2,
      'player.y': canvasHeight - 100
    });
  },

  // 初始化动画
  initAnimations() {
    const animations = {};
    
    // 玩家移动动画
    animations.playerMove = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    });
    
    // 得分动画
    animations.scorePopup = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    });
    
    this.setData({ animations });
  },

  // 加载游戏统计
  loadGameStats() {
    const savedStats = wx.getStorageSync('thief_game_stats');
    if (savedStats) {
      this.setData({ gameStats: savedStats });
    }
  },

  // 保存游戏统计
  saveGameStats() {
    wx.setStorageSync('thief_game_stats', this.data.gameStats);
  },

  // 开始游戏
  startGame() {
    this.setData({
      'gameState.isPlaying': true,
      'gameState.isPaused': false,
      'gameState.level': 1,
      'gameState.score': 0,
      'gameState.lives': 3,
      'gameState.timeRemaining': 60,
      'gameState.combo': 0,
      'gameState.maxCombo': 0,
      emotions: [],
      powerUps: [],
      particles: [],
      showGameOver: false,
      showPause: false
    });
    
    // 重置玩家位置
    this.setData({
      'player.x': this.data.gameConfig.canvasWidth / 2,
      'player.y': this.data.gameConfig.canvasHeight - 100,
      'player.invulnerable': false,
      'player.powerUp': null,
      'player.powerUpTime': 0
    });
    
    // 开始游戏循环
    this.gameLoop();
    
    // 开始计时器
    this.startTimer();
    
    // 播放背景音乐
    this.playBackgroundMusic();
    
    wx.showToast({
      title: '游戏开始！',
      icon: 'success',
      duration: 1000
    });
  },

  // 游戏主循环
  gameLoop() {
    if (!this.data.gameState.isPlaying || this.data.gameState.isPaused) {
      return;
    }
    
    // 更新游戏对象
    this.updateEmotions();
    this.updatePowerUps();
    this.updateParticles();
    this.updatePlayer();
    
    // 生成新对象
    this.spawnEmotions();
    this.spawnPowerUps();
    
    // 检测碰撞
    this.checkCollisions();
    
    // 渲染游戏
    this.render();
    
    // 继续循环
    requestAnimationFrame(() => this.gameLoop());
  },

  // 更新情感物品
  updateEmotions() {
    const emotions = this.data.emotions.map(emotion => {
      emotion.y += emotion.speed * this.data.gameConfig.emotionSpeed;
      
      // 应用道具效果
      if (this.data.player.powerUp === 'slowMotion') {
        emotion.y -= emotion.speed * 0.5;
      }
      
      if (this.data.player.powerUp === 'attract' && emotion.points > 0) {
        const dx = this.data.player.x - emotion.x;
        const dy = this.data.player.y - emotion.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < 150) {
          emotion.x += dx * 0.1;
          emotion.y += dy * 0.1;
        }
      }
      
      return emotion;
    }).filter(emotion => emotion.y < this.data.gameConfig.canvasHeight + 50);
    
    this.setData({ emotions });
  },

  // 更新道具
  updatePowerUps() {
    const powerUps = this.data.powerUps.map(powerUp => {
      powerUp.y += 2;
      return powerUp;
    }).filter(powerUp => powerUp.y < this.data.gameConfig.canvasHeight + 50);
    
    this.setData({ powerUps });
    
    // 更新玩家道具状态
    if (this.data.player.powerUp && this.data.player.powerUpTime > 0) {
      const newTime = this.data.player.powerUpTime - 16; // 假设60fps
      if (newTime <= 0) {
        this.setData({
          'player.powerUp': null,
          'player.powerUpTime': 0
        });
      } else {
        this.setData({ 'player.powerUpTime': newTime });
      }
    }
  },

  // 更新粒子效果
  updateParticles() {
    const particles = this.data.particles.map(particle => {
      particle.x += particle.vx;
      particle.y += particle.vy;
      particle.life -= 1;
      particle.alpha = particle.life / particle.maxLife;
      return particle;
    }).filter(particle => particle.life > 0);
    
    this.setData({ particles });
  },

  // 更新玩家
  updatePlayer() {
    // 无敌时间处理
    if (this.data.player.invulnerable) {
      setTimeout(() => {
        this.setData({ 'player.invulnerable': false });
      }, 2000);
    }
    
    // 道具效果时间处理
    if (this.data.player.powerUp && this.data.player.powerUpTime > 0) {
      const newTime = this.data.player.powerUpTime - 16; // 假设60fps
      if (newTime <= 0) {
        this.setData({
          'player.powerUp': null,
          'player.powerUpTime': 0
        });
      } else {
        this.setData({ 'player.powerUpTime': newTime });
      }
    }
  },

  // 生成情感物品
  spawnEmotions() {
    if (Math.random() < this.data.gameConfig.spawnRate * (1 + this.data.gameState.level * 0.1)) {
      const emotionType = this.data.emotionTypes[Math.floor(Math.random() * this.data.emotionTypes.length)];
      
      const emotion = {
        id: Date.now() + Math.random(),
        x: Math.random() * (this.data.gameConfig.canvasWidth - 40) + 20,
        y: -40,
        width: 40,
        height: 40,
        ...emotionType,
        speed: emotionType.speed * (1 + this.data.gameState.level * 0.1)
      };
      
      this.setData({
        emotions: [...this.data.emotions, emotion]
      });
    }
  },

  // 生成道具
  spawnPowerUps() {
    if (Math.random() < this.data.gameConfig.powerUpRate) {
      const powerUpType = this.data.powerUpTypes[Math.floor(Math.random() * this.data.powerUpTypes.length)];
      
      const powerUp = {
        id: Date.now() + Math.random(),
        x: Math.random() * (this.data.gameConfig.canvasWidth - 40) + 20,
        y: -40,
        width: 40,
        height: 40,
        ...powerUpType
      };
      
      this.setData({
        powerUps: [...this.data.powerUps, powerUp]
      });
    }
  },

  // 检测碰撞
  checkCollisions() {
    const player = this.data.player;
    
    // 检测情感物品碰撞
    let newEmotions = [...this.data.emotions];
    let newScore = this.data.gameState.score;
    let newCombo = this.data.gameState.combo;
    let newMaxCombo = this.data.gameState.maxCombo;
    let newLives = this.data.gameState.lives;
    
    for (let i = newEmotions.length - 1; i >= 0; i--) {
      if (this.isColliding(player, newEmotions[i])) {
        // 处理情感物品收集
        let points = newEmotions[i].points;
        
        // 应用道具效果
        if (this.data.player.powerUp === 'doublePoints' && points > 0) {
          points *= 2;
        }
        
        if (points > 0) {
          // 收集正面情感
          newCombo += 1;
          newScore += points + (newCombo * 2);
          newMaxCombo = Math.max(newMaxCombo, newCombo);
          
          // 创建得分粒子效果
          this.createScoreParticles(newEmotions[i].x, newEmotions[i].y, points, newEmotions[i].color);
        } else {
          // 收到负面情感
          if (!this.data.player.invulnerable && this.data.player.powerUp !== 'shield') {
            newLives -= 1;
            newCombo = 0;
            // 创建伤害效果
            this.createDamageParticles(newEmotions[i].x, newEmotions[i].y);
            
            // 播放伤害音效
            this.playSound('damage');
          }
        }
        
        newEmotions.splice(i, 1);
        
        // 检查游戏结束
        if (newLives <= 0) {
          this.gameOver();
          return;
        }
      }
    }
    
    // 检测道具碰撞
    let newPowerUps = [...this.data.powerUps];
    for (let i = newPowerUps.length - 1; i >= 0; i--) {
      if (this.isColliding(player, newPowerUps[i])) {
        // 激活道具效果
        this.setData({
          'player.powerUp': newPowerUps[i].effect,
          'player.powerUpTime': newPowerUps[i].duration
        });
        
        // 创建道具效果
        this.createPowerUpParticles(newPowerUps[i].x, newPowerUps[i].y);
        
        // 播放道具音效
        this.playSound('powerup');
        
        wx.showToast({
          title: `获得${this.getPowerUpName(newPowerUps[i].effect)}！`,
          icon: 'none',
          duration: 1500
        });
        
        newPowerUps.splice(i, 1);
      }
    }
    
    // 更新状态
    this.setData({
      emotions: newEmotions,
      powerUps: newPowerUps,
      'gameState.score': newScore,
      'gameState.combo': newCombo,
      'gameState.maxCombo': newMaxCombo,
      'gameState.lives': newLives
    });
    
    // 检查升级
    this.checkLevelUp();
  },

  // 碰撞检测
  isColliding(obj1, obj2) {
    return obj1.x < obj2.x + obj2.width &&
           obj1.x + obj1.width > obj2.x &&
           obj1.y < obj2.y + obj2.height &&
           obj1.y + obj1.height > obj2.y;
  },

  // 收集情感
  collectEmotion(emotion, index) {
    const emotions = [...this.data.emotions];
    emotions.splice(index, 1);
    this.setData({ emotions });
    
    let points = emotion.points;
    
    // 应用道具效果
    if (this.data.player.powerUp === 'doublePoints' && points > 0) {
      points *= 2;
    }
    
    if (points > 0) {
      // 正面情感
      const newCombo = this.data.gameState.combo + 1;
      const newScore = this.data.gameState.score + points + (newCombo * 2);
      
      this.setData({
        'gameState.score': newScore,
        'gameState.combo': newCombo,
        'gameState.maxCombo': Math.max(this.data.gameState.maxCombo, newCombo)
      });
      
      // 创建得分粒子效果
      this.createScoreParticles(emotion.x, emotion.y, points, emotion.color);
      
      // 播放收集音效
      this.playSound('collect');
      
    } else {
      // 负面情感
      if (!this.data.player.invulnerable && this.data.player.powerUp !== 'shield') {
        const newLives = this.data.gameState.lives - 1;
        this.setData({
          'gameState.lives': newLives,
          'gameState.combo': 0,
          'player.invulnerable': true
        });
        
        // 创建伤害效果
        this.createDamageParticles(emotion.x, emotion.y);
        
        // 播放伤害音效
        this.playSound('damage');
        
        // 检查游戏结束
        if (newLives <= 0) {
          this.gameOver();
          return;
        }
      }
    }
    
    // 检查升级
    this.checkLevelUp();
  },

  // 收集道具
  collectPowerUp(powerUp, index) {
    const powerUps = [...this.data.powerUps];
    powerUps.splice(index, 1);
    this.setData({ powerUps });
    
    // 激活道具效果
    this.setData({
      'player.powerUp': powerUp.effect,
      'player.powerUpTime': powerUp.duration
    });
    
    // 创建道具效果
    this.createPowerUpParticles(powerUp.x, powerUp.y);
    
    // 播放道具音效
    this.playSound('powerup');
    
    wx.showToast({
      title: `获得${this.getPowerUpName(powerUp.effect)}！`,
      icon: 'none',
      duration: 1500
    });
  },

  // 获取道具名称
  getPowerUpName(effect) {
    const names = {
      invulnerable: '无敌护盾',
      attract: '情感磁铁',
      slowMotion: '时间减缓',
      doublePoints: '双倍得分'
    };
    return names[effect] || '神秘道具';
  },

  // 创建得分粒子效果
  createScoreParticles(x, y, points, color) {
    const particles = [];
    for (let i = 0; i < 5; i++) {
      particles.push({
        x: x + Math.random() * 20 - 10,
        y: y + Math.random() * 20 - 10,
        vx: Math.random() * 4 - 2,
        vy: Math.random() * 4 - 2,
        life: 30,
        maxLife: 30,
        alpha: 1,
        color: color,
        text: `+${points}`
      });
    }
    
    this.setData({
      particles: [...this.data.particles, ...particles]
    });
    
    // 添加得分动画
    const scoreAnimation = this.data.animations.scorePopup.export();
    this.setData({ scoreAnimation });
  },

  // 创建伤害粒子效果
  createDamageParticles(x, y) {
    const particles = [];
    for (let i = 0; i < 8; i++) {
      particles.push({
        x: x + Math.random() * 30 - 15,
        y: y + Math.random() * 30 - 15,
        vx: Math.random() * 6 - 3,
        vy: Math.random() * 6 - 3,
        life: 20,
        maxLife: 20,
        alpha: 1,
        color: '#FF4500',
        text: '💥'
      });
    }
    
    this.setData({
      particles: [...this.data.particles, ...particles]
    });
  },

  // 创建道具粒子效果
  createPowerUpParticles(x, y) {
    const particles = [];
    for (let i = 0; i < 10; i++) {
      particles.push({
        x: x + Math.random() * 40 - 20,
        y: y + Math.random() * 40 - 20,
        vx: Math.random() * 8 - 4,
        vy: Math.random() * 8 - 4,
        life: 40,
        maxLife: 40,
        alpha: 1,
        color: '#FFD700',
        text: '✨'
      });
    }
    
    this.setData({
      particles: [...this.data.particles, ...particles]
    });
  },

  // 检查升级
  checkLevelUp() {
    const requiredScore = this.data.gameState.level * 500;
    if (this.data.gameState.score >= requiredScore) {
      this.setData({
        'gameState.level': this.data.gameState.level + 1,
        'gameState.timeRemaining': this.data.gameState.timeRemaining + 10
      });
      
      wx.showToast({
        title: `升级到第${this.data.gameState.level}关！`,
        icon: 'success',
        duration: 2000
      });
      
      this.playSound('levelup');
    }
  },

  // 开始计时器
  startTimer() {
    this.timer = setInterval(() => {
      if (!this.data.gameState.isPlaying || this.data.gameState.isPaused) {
        return;
      }
      
      const newTime = this.data.gameState.timeRemaining - 1;
      this.setData({ 'gameState.timeRemaining': newTime });
      
      if (newTime <= 0) {
        this.gameOver();
      }
    }, 1000);
  },

  // 暂停游戏
  pauseGame() {
    this.setData({
      'gameState.isPaused': true,
      showPause: true
    });
    
    this.pauseBackgroundMusic();
  },

  // 恢复游戏
  resumeGame() {
    this.setData({
      'gameState.isPaused': false,
      showPause: false
    });
    
    this.resumeBackgroundMusic();
    this.gameLoop();
  },

  // 游戏结束
  gameOver() {
    this.setData({
      'gameState.isPlaying': false,
      showGameOver: true
    });
    
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    // 更新统计数据
    this.updateGameStats();
    
    // 停止背景音乐
    this.stopBackgroundMusic();
    
    // 播放游戏结束音效
    this.playSound('gameover');
    
    // 显示游戏结束动画
    const gameOverAnimation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease-out'
    });
    gameOverAnimation.opacity(1).scale(1, 1).step();
    this.setData({ gameOverAnimation: gameOverAnimation.export() });
  },

  // 更新游戏统计
  updateGameStats() {
    const stats = { ...this.data.gameStats };
    
    stats.totalGames += 1;
    stats.bestScore = Math.max(stats.bestScore, this.data.gameState.score);
    stats.totalEmotionsCaught += Math.floor(this.data.gameState.score / 10); // 更准确的估算
    stats.totalTimePlayed += 60 - this.data.gameState.timeRemaining;
    
    // 计算更准确的平均连击
    stats.averageCombo = (stats.averageCombo * stats.totalGames + this.data.gameState.maxCombo) / 
                        (stats.totalGames + 1);
    
    this.setData({ gameStats: stats });
    this.saveGameStats();
    
    // 更新排行榜
    this.updateLeaderboard();
  },

  // 更新排行榜
  updateLeaderboard() {
    const leaderboard = [...this.data.leaderboard];
    const playerIndex = leaderboard.findIndex(entry => entry.name === '你');
    
    if (playerIndex !== -1) {
      leaderboard[playerIndex].score = Math.max(leaderboard[playerIndex].score, this.data.gameState.score);
      leaderboard[playerIndex].level = Math.max(leaderboard[playerIndex].level, this.data.gameState.level);
    }
    
    // 排序
    leaderboard.sort((a, b) => b.score - a.score);
    
    // 重新分配排名
    leaderboard.forEach((entry, index) => {
      entry.rank = index + 1;
    });
    
    this.setData({ leaderboard });
  },

  // 渲染游戏
  render() {
    const ctx = this.ctx;
    
    // 清空画布
    ctx.clearRect(0, 0, this.data.gameConfig.canvasWidth, this.data.gameConfig.canvasHeight);
    
    // 绘制背景
    this.drawBackground(ctx);
    
    // 绘制情感物品
    this.data.emotions.forEach(emotion => {
      this.drawEmotion(ctx, emotion);
    });
    
    // 绘制道具
    this.data.powerUps.forEach(powerUp => {
      this.drawPowerUp(ctx, powerUp);
    });
    
    // 绘制玩家
    this.drawPlayer(ctx);
    
    // 绘制粒子效果
    this.data.particles.forEach(particle => {
      this.drawParticle(ctx, particle);
    });
    
    // 提交绘制
    ctx.draw();
  },

  // 绘制背景
  drawBackground(ctx) {
    const gradient = ctx.createLinearGradient(0, 0, 0, this.data.gameConfig.canvasHeight);
    gradient.addColorStop(0, '#0f0f23');
    gradient.addColorStop(1, '#2d1b69');
    
    ctx.setFillStyle(gradient);
    ctx.fillRect(0, 0, this.data.gameConfig.canvasWidth, this.data.gameConfig.canvasHeight);
  },

  // 绘制情感
  drawEmotion(ctx, emotion) {
    ctx.setFillStyle(emotion.color);
    ctx.fillRect(emotion.x, emotion.y, emotion.width, emotion.height);
    
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(24);
    ctx.setTextAlign('center');
    ctx.fillText(emotion.emoji, emotion.x + emotion.width / 2, emotion.y + emotion.height / 2 + 8);
  },

  // 绘制道具
  drawPowerUp(ctx, powerUp) {
    ctx.setFillStyle('#FFD700');
    ctx.fillRect(powerUp.x, powerUp.y, powerUp.width, powerUp.height);
    
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(24);
    ctx.setTextAlign('center');
    ctx.fillText(powerUp.emoji, powerUp.x + powerUp.width / 2, powerUp.y + powerUp.height / 2 + 8);
  },

  // 绘制玩家
  drawPlayer(ctx) {
    const player = this.data.player;
    
    // 无敌状态闪烁效果
    if (player.invulnerable && Math.floor(Date.now() / 100) % 2) {
      ctx.setGlobalAlpha(0.5);
    }
    
    // 道具效果
    if (player.powerUp === 'shield') {
      ctx.setFillStyle('rgba(0, 255, 255, 0.3)');
      ctx.fillRect(player.x - 10, player.y - 10, player.width + 20, player.height + 20);
    }
    
    ctx.setFillStyle('#8a2be2');
    ctx.fillRect(player.x, player.y, player.width, player.height);
    
    ctx.setFillStyle('#ffffff');
    ctx.setFontSize(32);
    ctx.setTextAlign('center');
    ctx.fillText(player.emoji, player.x + player.width / 2, player.y + player.height / 2 + 10);
    
    ctx.setGlobalAlpha(1);
  },

  // 绘制粒子
  drawParticle(ctx, particle) {
    ctx.setGlobalAlpha(particle.alpha);
    ctx.setFillStyle(particle.color);
    ctx.setFontSize(16);
    ctx.setTextAlign('center');
    ctx.fillText(particle.text, particle.x, particle.y);
    ctx.setGlobalAlpha(1);
  },

  // 触摸开始
  onTouchStart(e) {
    if (!this.data.gameState.isPlaying || this.data.gameState.isPaused) {
      return;
    }
    
    this.setData({
      touchStartX: e.touches[0].x,
      touchStartY: e.touches[0].y
    });
  },

  // 触摸移动
  onTouchMove(e) {
    if (!this.data.gameState.isPlaying || this.data.gameState.isPaused) {
      return;
    }
    
    const deltaX = e.touches[0].x - this.data.touchStartX;
    const deltaY = e.touches[0].y - this.data.touchStartY;
    
    let newX = this.data.player.x + deltaX;
    let newY = this.data.player.y + deltaY;
    
    // 边界检测
    newX = Math.max(0, Math.min(newX, this.data.gameConfig.canvasWidth - this.data.player.width));
    newY = Math.max(0, Math.min(newY, this.data.gameConfig.canvasHeight - this.data.player.height));
    
    this.setData({
      'player.x': newX,
      'player.y': newY,
      touchStartX: e.touches[0].x,
      touchStartY: e.touches[0].y
    });
  },

  // 播放音效
  playSound(type) {
    if (!this.data.soundEnabled) return;
    
    const soundMap = {
      collect: '/sounds/collect.mp3',
      damage: '/sounds/damage.mp3',
      powerup: '/sounds/powerup.mp3',
      levelup: '/sounds/levelup.mp3',
      gameover: '/sounds/gameover.mp3'
    };
    
    if (soundMap[type]) {
      const audio = wx.createInnerAudioContext();
      audio.src = soundMap[type];
      audio.play();
    }
  },

  // 播放背景音乐
  playBackgroundMusic() {
    if (!this.data.soundEnabled) return;
    
    this.bgMusic = wx.createInnerAudioContext();
    this.bgMusic.src = '/sounds/game-bg.mp3';
    this.bgMusic.loop = true;
    this.bgMusic.play();
  },

  // 暂停背景音乐
  pauseBackgroundMusic() {
    if (this.bgMusic) {
      this.bgMusic.pause();
    }
  },

  // 恢复背景音乐
  resumeBackgroundMusic() {
    if (this.bgMusic) {
      this.bgMusic.play();
    }
  },

  // 停止背景音乐
  stopBackgroundMusic() {
    if (this.bgMusic) {
      this.bgMusic.stop();
      this.bgMusic.destroy();
      this.bgMusic = null;
    }
  },

  // 重新开始游戏
  onRestartGame() {
    this.startGame();
  },

  // 返回主菜单
  onBackToMenu() {
    this.setData({
      'gameState.isPlaying': false,
      showGameOver: false,
      showPause: false
    });
    
    this.stopBackgroundMusic();
    
    if (this.timer) {
      clearInterval(this.timer);
    }
  },

  // 显示说明
  onShowInstructions() {
    this.setData({ showInstructions: true });
  },

  // 隐藏说明
  onHideInstructions() {
    this.setData({ showInstructions: false });
  },

  // 显示排行榜
  onShowLeaderboard() {
    this.setData({ showLeaderboard: true });
  },

  // 隐藏排行榜
  onHideLeaderboard() {
    this.setData({ showLeaderboard: false });
  },

  // 切换音效
  onToggleSound() {
    this.setData({ soundEnabled: !this.data.soundEnabled });
    
    if (!this.data.soundEnabled) {
      this.stopBackgroundMusic();
    } else if (this.data.gameState.isPlaying && !this.data.gameState.isPaused) {
      this.playBackgroundMusic();
    }
  },

  // 分享游戏
  onShareGame() {
    return {
      title: `我在心情追回游戏中得了${this.data.gameState.score}分！`,
      path: '/pages/thief/game/index',
      imageUrl: '/images/game-share.png'
    };
  }
});